package jiang.Algorithm;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName TestStream
 * @Description: 使用流对集合分组
 * @Author jiangshitao
 * @Date 2023/1/31
 */
public class TestStream {
    List<Integer> numberList = Arrays.asList(3, 5, 6, 4, 2, 8, 9, 1, 7);

    /**
     * 用Stream流进行分组
     */
    public void groupByStream() {
        long startTime = System.currentTimeMillis();
        //使用stream流进行分组（使用条件）
        Map<Boolean, List<Integer>> splitMap = numberList
                .stream()
                .collect(Collectors.groupingBy(number -> number < 5));
        // 满足条件的一组
        List<Integer> trueList = splitMap.get(true);
        // 不满足条件的一组
        List<Integer> falseList = splitMap.get(false);
        long endTime = System.currentTimeMillis();
        System.out.println("共耗时：" + (endTime-startTime) + "ms");
        System.out.println(trueList.toString());
        System.out.println(falseList.toString());
    }


    /**
     * 用增强for循环分组
     */
    public void groupByFor() {
        long startTime = System.currentTimeMillis();
        List<Integer> trueList = new ArrayList<>();
        List<Integer> falseList = new ArrayList<>();
        for (int num : numberList) {
            if (num < 5) {
                trueList.add(num);
            }else {
                falseList.add(num);
            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println("共耗时：" + (endTime-startTime) + "ms");
        System.out.println(trueList);
        System.out.println(falseList);
    }

    public static void main(String[] args) {
        // 我不理解为啥要用流来分组
        // 按结果来看增强型for循环效率要高得多
        TestStream testStream = new TestStream();
        testStream.groupByStream();
        testStream.groupByFor();
    }
}
